import {
  login,
  logout,
  getInfo,
  checkIdentifyCanReg,
  reg,
  queryAllUserList,
  queryUserProfile,
  updateUserProfile
} from '@/api/users/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
import * as outils from "outils";

const getDefaultState = () => {
  return {
    token: getToken(),
    realName: '',
    avatar: '',
    roles: [],
    uid: -1
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.realName = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_UID: (state, uid) => {
    state.uid = uid;
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    const {identify, password, token, code} = userInfo
    return new Promise((resolve, reject) => {
      login(identify.trim(), password, token, code).then(response => {
        console.log("-------login action success------------")
        console.log(response);
        //const { data } = response
        //想办法从cookie或者satoken令牌，服务器写到cookie里的。
        commit('SET_TOKEN', outils.getCookie("satoken"))
        setToken(outils.getCookie("satoken"))
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        //const {name, avatar} = data
        const {roles, realName, avatar, uid} = data
        // roles must be a non-empty array

        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
          //commit('SET_ROLES', [])
        }

        console.log("----------获取登录成功的用户资料--------------")
        console.log(data);

        commit('SET_ROLES', roles)
        commit('SET_NAME', realName)
        commit('SET_AVATAR', avatar)
        commit('SET_UID', uid)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((response) => {
        commit('SET_ROLES', [])
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_ROLES', [])
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  //检查手机或者邮箱是否已经注册
  checkIdentifyCanReg({commit, state}, identify) {
    return new Promise((resolve, reject) => {
      //调用真正的接口
      checkIdentifyCanReg(identify).then(resp => {
        resolve(resp);
      }).catch(err => {
        reject(err);
      })
    })
  },

  //用户注册
  reg({commit, state}, user) {
    return new Promise((resolve, reject) => {
      reg(user).then(resp => {
        resolve(resp);
      }).catch(err => {
        reject(err);
      })
    })
  },

  //查询所有用户资料
  queryAllUserList({commit, state}) {
    return new Promise((resolve, reject) => {
      queryAllUserList().then(resp => {
        resolve(resp);
      }).catch(err => {
        reject(err);
      })
    })
  },

  queryUserProfile({commit, state}, uid) {
    return new Promise((resolve, reject) => {
      queryUserProfile(uid).then(resp => {
        resolve(resp);
      }).catch(err => {
        reject(err);
      })
    })
  },

  updateUserProfile({commit, state}, user) {
    return new Promise((resolve, reject) => {
      updateUserProfile(user).then(resp => {
        commit('SET_AVATAR', user.avatar)
        resolve(resp);
      }).catch(err => {
        reject(err);
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

